package com.sddnytsh.body_buildingsystem.network

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.topic.CommunityPost
import android.util.Log
import java.io.IOException

/**
 * 分段式数据加载服务 - 解决帖子详情页性能问题
 */
object SegmentedDataService {
    
    private val client = OkHttpClient.Builder()
        .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
        .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
        .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .connectionPool(ConnectionPool(5, 30, java.util.concurrent.TimeUnit.SECONDS))
        .build()
    
    private val gson = Gson()
    
    /**
     * 快速加载帖子详情（暂时使用原有接口，但限制评论数量）
     */
    suspend fun getPostDetailQuick(postId: Int, currentUserId: Long? = null): PostDetailQuickResult {
        return withContext(Dispatchers.IO) {
            try {
                // 使用原有接口，但限制评论数量
                val url = "${NetworkConfig.BASE_URL}/api/community-posts/$postId" +
                        if (currentUserId != null) "?currentUserId=$currentUserId" else ""
                
                val request = Request.Builder()
                    .url(url)
                    .get()
                    .build()
                
                Log.d("SegmentedDataService", "快速加载帖子详情: postId=$postId, currentUserId=$currentUserId")
                
                val response = client.newCall(request).execute()
                val responseBody = response.body?.string()
                
                if (response.isSuccessful && responseBody != null) {
                    Log.d("SegmentedDataService", "快速加载响应: $responseBody")
                    
                    // 解析原有接口的响应格式
                    val apiResponse = gson.fromJson(responseBody, object : TypeToken<ApiResponse<CommunityPost>>() {}.type) as ApiResponse<CommunityPost>
                    
                    if (apiResponse.success) {
                        val post = apiResponse.data
                        
                        // 获取评论列表（限制前10条）
                        val commentsResult = getCommentsByPostIdLimited(postId, currentUserId, 10)
                        
                        val quickData = PostDetailQuickData(
                            post = post,
                            comments = commentsResult,
                            totalComments = commentsResult.size // 暂时使用实际返回的评论数
                        )
                        
                        Log.d("SegmentedDataService", "快速加载成功: postId=$postId, 评论=${commentsResult.size}条")
                        PostDetailQuickResult.Success(quickData)
                    } else {
                        Log.w("SegmentedDataService", "快速加载失败: postId=$postId, message=${apiResponse.message}")
                        PostDetailQuickResult.Error(apiResponse.message ?: "快速加载失败")
                    }
                } else {
                    Log.e("SegmentedDataService", "快速加载网络错误: postId=$postId, code=${response.code}")
                    PostDetailQuickResult.Error("网络请求失败: ${response.code}")
                }
            } catch (e: Exception) {
                Log.e("SegmentedDataService", "快速加载异常: postId=$postId", e)
                PostDetailQuickResult.Error("请求异常: ${e.message}")
            }
        }
    }
    
    /**
     * 获取帖子评论（限制数量）
     */
    private suspend fun getCommentsByPostIdLimited(postId: Int, currentUserId: Long?, limit: Int): List<Comment> {
        return withContext(Dispatchers.IO) {
            try {
                val url = "${NetworkConfig.BASE_URL}/api/post-comments/post/$postId" +
                        if (currentUserId != null) "?currentUserId=$currentUserId" else ""
                
                val request = Request.Builder()
                    .url(url)
                    .get()
                    .build()
                
                val response = client.newCall(request).execute()
                val responseBody = response.body?.string()
                
                if (response.isSuccessful && responseBody != null) {
                    val apiResponse = gson.fromJson(responseBody, object : TypeToken<ApiResponse<Map<String, Any>>>() {}.type) as ApiResponse<Map<String, Any>>
                    
                    if (apiResponse.success) {
                        val commentsData = apiResponse.data["comments"] as? List<Map<String, Any>> ?: emptyList()
                        val limitedComments = commentsData.take(limit).map { commentMap ->
                            Comment(
                                id = (commentMap["id"] as? Number)?.toLong() ?: 0L,
                                postId = (commentMap["postId"] as? Number)?.toLong() ?: 0L,
                                userId = (commentMap["userId"] as? Number)?.toLong() ?: 0L,
                                content = commentMap["content"] as? String ?: "",
                                likeCount = (commentMap["likeCount"] as? Number)?.toInt() ?: 0,
                                isLiked = commentMap["isLiked"] as? Boolean ?: false,
                                createdAt = commentMap["createdAt"] as? String ?: "",
                                author = commentMap["author"] as? String ?: "匿名用户",
                                parentId = (commentMap["parentId"] as? Number)?.toLong(),
                                rootId = (commentMap["rootId"] as? Number)?.toLong(),
                                isDeleted = commentMap["isDeleted"] as? Boolean ?: false
                            )
                        }
                        limitedComments
                    } else {
                        emptyList()
                    }
                } else {
                    emptyList()
                }
            } catch (e: Exception) {
                Log.e("SegmentedDataService", "获取评论异常: postId=$postId", e)
                emptyList()
            }
        }
    }
    
    /**
     * 后台补充加载剩余评论（暂时禁用，等待后端重启）
     */
    suspend fun getPostComments(postId: Int, offset: Int = 10, limit: Int = 20, currentUserId: Long? = null): PostCommentsResult {
        return withContext(Dispatchers.IO) {
            try {
                Log.d("SegmentedDataService", "后台加载评论暂时禁用: postId=$postId, offset=$offset, limit=$limit")
                
                // 暂时返回空列表，等待后端重启后启用分段式接口
                PostCommentsResult.Success(emptyList())
            } catch (e: Exception) {
                Log.e("SegmentedDataService", "后台加载评论异常: postId=$postId", e)
                PostCommentsResult.Error("请求异常: ${e.message}")
            }
        }
    }
}

/**
 * 快速加载结果
 */
sealed class PostDetailQuickResult {
    data class Success(val data: PostDetailQuickData) : PostDetailQuickResult()
    data class Error(val message: String) : PostDetailQuickResult()
}

/**
 * 评论加载结果
 */
sealed class PostCommentsResult {
    data class Success(val comments: List<Comment>) : PostCommentsResult()
    data class Error(val message: String) : PostCommentsResult()
}

/**
 * API响应结构
 */
data class ApiResponse<T>(
    val success: Boolean,
    val message: String?,
    val data: T
)

/**
 * 快速加载数据
 */
data class PostDetailQuickData(
    val post: CommunityPost,
    val comments: List<Comment>,
    val totalComments: Int
)

/**
 * 评论数据
 */
data class PostCommentsData(
    val comments: List<Comment>,
    val hasMore: Boolean
)
